package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service//作用：暴露服务。
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
     private MemberMapper memberMapper;
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Autowired
    JavaMailSender mailSender;
    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
         UserRegisterResponse registerResponse=new UserRegisterResponse();
        //判空
       registerRequest.requestCheck();
       //验证用户名是否重复
       userNameRepeat(registerRequest);
       //1.向用户表中插入一条记录
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());
        //对password加密处理
        String userpassword = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        member.setPassword(userpassword);

        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        //钱包的状态
        member.setState(1);

        int effectRows=memberMapper.insert(member);
        if(effectRows!=1){
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return registerResponse;
        }
//向用户验证表中插入一条记录
        UserVerify userVerify=new UserVerify();
        userVerify.setUsername(member.getUsername());
        String key= member.getUsername()+member.getPassword()+ UUID.randomUUID().toString();
        String uuid=DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");

        int insertRows = userVerifyMapper.insert(userVerify);
        if(insertRows!=1){
            registerResponse.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            registerResponse.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return registerResponse;
        }
           //发送邮件
        sendEmail(uuid,registerRequest);
        //打印日志
        log.info("用户注册成功，注册参数request：{}", JSON.toJSONString(registerRequest));
        registerResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        registerResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        return registerResponse;

    }

    /**
     * 发送激活邮件
     * @param uuid
     * @param registerRequest
     */
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("多来买商城用户激活 ");
        simpleMailMessage.setFrom("javaxiangmu3@163.com");
        simpleMailMessage.setTo(registerRequest.getEmail());
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("http://localhost:8080/user/verify?uid=").append(uuid).append("&username=").append(registerRequest.getUserName());
        simpleMailMessage.setText(stringBuilder.toString());
        mailSender.send(simpleMailMessage);
    }

    //判断用户名是否重复的判断方法
    private void userNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());
        //select *from tb_member where username=#{username}
        List<Member> members = memberMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(members)){
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants
            .USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
